var game = cc.Class({
  extends: cc.Component,
  properties: () => ({
    // 预制件管理
    preMan: {
      default: null,
      type: require("preMan")
    },
    // 背景音乐
    gameBgAudio: {
      default: null,
      type: cc.AudioClip
    },
    // 暂停界面
    stopPanel: {
      default: null,
      type: cc.Node
    },
    // 结束 成功 选择分享获得道具页面
    getPanel: {
      default: null,
      type: cc.Node
    },
    itemget: {
      default: null,
      type: cc.Sprite
    },
    // 选择分享获得锦鲤页面
    jinliPanel: {
      default: null,
      type: cc.Node
    },
    // 结束页面
    endPanel: {
      default: null,
      type: cc.Node
    },
    // 时间条
    totalTimeBar: {
      default: null,
      type: cc.Node
    },
    // 火力条
    totalPowTimeBar: {
      default: null,
      type: cc.Node
    },
    // 火苗
    fire: {
      default: null,
      type: cc.Node
    },
    // 道具 时钟 功能加时
    clock_item: {
      default: null,
      type: cc.Label
    },
    // 道具 大火 大火时间维持
    powFire_item: {
      default: null,
      type: cc.Label
    },
    // 道具 水 小火时间维持
    water_item: {
      default: null,
      type: cc.Label
    },
    // 道具 金币翻倍
    doubleCoin_item: {
      default: null,
      type: cc.Label
    },
    // 金币
    money: {
      default: null,
      type: cc.Label
    },
    // 加分
    moneyDisplay: {
      default: null,
      type: cc.Node
    }
  }),
  onLoad: function() {
    this.stopPanel.active = false;
    this.endPanel.active = false;
    this.getPanel.active = false;
    this.jinliPanel.active = false;
    Globals.gameRun = true; // 判断游戏开始或结束
    Globals.powerBS = 1.0; // 判断火力大小 使用功率计算
    cc.audioEngine.play(this.gameBgAudio, true);        // 播放音乐
    this.timeCount = 0; // 倒计时扣除时间
    this.totalTimeCount = 180; // 倒计时总时间
    this.powTime = 0; // 火力时间计时
    this.money.string = '0'; // 初始金币为0
    this.powBigTime = 10; // 道具大火时效初始 10秒
    this.powSomleTime = 30; // 道具小火时效初始 30秒
    Globals.resultCoin = 1; // 道具双倍金币效果 初始1倍
    this.updateCloud(); // 更新云端数据
    // 云接入口开启
    wx.cloud.init({
      traceUser: true
    });
  },
  // 云函数返回userid 
  updateCloud: function() {
    var _self = this;
    // 云函数 获取 openid或者appid
    wx.cloud.callFunction({
      name: 'Moyu',
      complete: res => {
        _self.OPENID = res.result.userInfo.openId;
        _self.getData(_self.OPENID);
        console.log('获取用户id111: ', _self.OPENID);
      }
    });
  },
  // 云端获得道具数据
  getData: function(OPENID) {
    var _self = this;
    console.log("获取云端数据", OPENID);
    const db = wx.cloud.database();
    db.collection('Moyu').where({
        _openid: OPENID,
      })
      .get({
        success: function(res) {
          _self._id = res.data[0]._id;
          _self.clockNum = res.data[0].clock;
          _self.powFireNum = res.data[0].powFire;
          _self.waterNum = res.data[0].water;
          _self.doubleCoinNum = res.data[0].doubleCoin;
          _self.clock_item.string = res.data[0].clock.toString();
          _self.powFire_item.string = res.data[0].powFire.toString();
          _self.water_item.string = res.data[0].water.toString();
          _self.doubleCoin_item.string = res.data[0].doubleCoin.toString();
          console.log("getData_success_get长度不为0", res.data[0]);
        },
        fail: function(res) {
          console.log("getData_fail_get", res);
        },
        complete: function(res) {
          console.log("getData_complete_get222", res);
        }
      })
  },
  // 时钟加时效果
  clockItemDisplay: function() {
    if (this.clockNum <= 0) return;
    else {
      this.clockNum -= 1;
      this.clock_item.string = this.clockNum.toString();
      this.totalTimeCount = 180;
      const db = wx.cloud.database();
      db.collection('Moyu').doc(this._id).update({
        data: {
          clock: this.clockNum
        }
      })
    }
  },
  // 大火力效果
  powFireItemDisplay: function() {
    if (this.powFireNum <= 0) return;
    else {
      this.powTime = 0;
      this.totalPowTimeBar.getComponent(cc.ProgressBar).progress = 1;
      this.powFireNum -= 1;
      this.powFire_item.string = this.powFireNum.toString();
      Globals.powerBS = 1.25;
      this.powBigTime = 30;
      const db = wx.cloud.database();
      db.collection('Moyu').doc(this._id).update({
        data: {
          powFire: this.powFireNum
        }
      })
    }
  },
  // 小火力效果
  waterItemDisplay: function() {
    if (this.waterNum <= 0) return;
    else {
      this.powTime = 0;
      this.totalPowTimeBar.getComponent(cc.ProgressBar).progress = 0.5;
      this.waterNum -= 1;
      this.water_item.string = this.waterNum.toString();
      Globals.powerBS = 1.0;
      this.powSomleTime = 30;
      const db = wx.cloud.database();
      db.collection('Moyu').doc(this._id).update({
        data: {
          water: this.waterNum
        }
      })
    }
  },
  // 双倍金币效果
  doubleCoinItemDisplay: function() {
    if (this.doubleCoinNum <= 0) return;
    else {
      if (Globals.resultCoin == 1) {
        this.doubleCoinNum -= 1;
        this.doubleCoin_item.string = this.doubleCoinNum.toString();
        Globals.resultCoin = 2;
        const db = wx.cloud.database();
        db.collection('Moyu').doc(this._id).update({
          data: {
            doubleCoin: this.doubleCoinNum
          }
        })
      } else {
        return;
      }
    }
  },
  update: function(dt) {
    if (!Globals.gameRun) return;
    // 时间计时器
    this.timeCount += dt;
    if (this.timeCount >= 1) {
      this.totalTimeCount -= 1;
      this.timeCount = 0;
      this.totalTimeBar.getComponent(cc.ProgressBar).progress = this.totalTimeCount / 180;
    }
    if (this.totalTimeCount <= 0) {
      this.gameOver();
    }
    // 火力计时器
    this.powTime += dt;
    if (Globals.powerBS == 1.0) {
      this.totalPowTimeBar.getComponent(cc.ProgressBar).progress = 0.5 + 0.5 * (this.powTime / this.powSomleTime);
      if (this.powTime >= this.powSomleTime) {
        this.powTime = 0.0;
        Globals.powerBS = 1.25;
      }
    } else if (Globals.powerBS == 1.25) {
      this.totalPowTimeBar.getComponent(cc.ProgressBar).progress = 1.0 - 0.5 * (this.powTime / this.powBigTime);
      if (this.powTime >= this.powBigTime) {
        this.powTime = 0.0;
        Globals.powerBS = 1.0;
      }
    }
  },
  // 加分特效显示
  getScore: function(sorce) {
    var sor = sorce.toString();
    this.moneyDisplay.getComponent(cc.Label).string = '+' + sor;
    if (!this.moneyDisplay.active) {
      this.moneyDisplay.active = true;
    }
    var animation = this.moneyDisplay.getComponent(cc.Animation);
    animation.playAdditive('mjia');
  },
  // 加分结算
  addScore: function(sorce) {
    cc.log(sorce, '单词分数');
    var curSource = parseInt(this.money.string);
    curSource += sorce;
    this.money.string = curSource.toString();
    cc.log(curSource, sorce, '前分数  后分数');
  },
  // 游戏结束
  gameOver: function() {
    Globals.gameRun = false;
    cc.audioEngine.stopAll();
    var curSource = parseInt(this.money.string);
    Globals.success = (curSource < 0) ? false : true;
    if (Globals.success) {
      this.getPanel.active = true;
      this.item = Math.ceil(Math.random() * 4);
      var spr = "resources/daoju/item" + this.item + ".png";
      if (this.item == 1) {
        this.getPanel.getChildByName('name').getComponent(cc.Label).string = '- 加时钟 -';
        this.getPanel.getChildByName('desc').getComponent(cc.Label).string = '- 效果：将剩余时间恢复至满 -';
      } else if (this.item == 2) {
        this.getPanel.getChildByName('name').getComponent(cc.Label).string = '- 火力全开 -';
        this.getPanel.getChildByName('desc').getComponent(cc.Label).string = '- 效果：让火炉保持最大火力 -';
      } else if (this.item == 3) {
        this.getPanel.getChildByName('name').getComponent(cc.Label).string = '- 冷却剂 -';
        this.getPanel.getChildByName('desc').getComponent(cc.Label).string = '- 效果：让火炉保持普通火力不变 -';
      } else if (this.item == 4) {
        this.getPanel.getChildByName('name').getComponent(cc.Label).string = '- 赚钱加倍 -';
        this.getPanel.getChildByName('desc').getComponent(cc.Label).string = '- 效果：使用后金币获取翻倍 -';
      }
      this.itemget.spriteFrame = new cc.SpriteFrame(cc.url.raw(spr));
    } else {
      this.item = 0;
      // this.endPanel.active = true;
      this.endPanelDisplay();
    }
  },
  // 道具跳转分享
  toShareItem: function() {
    var _this = this;
    //微信开启群分享
    wx.updateShareMenu({
      withShareTicket: true
    });
    wx.shareAppMessage({
      title: '好友'+ Globals.playername + '邀你玩烧烤之王，赢花语呢喃大奖',
      imageUrl: 'res/raw-assets/0e/0eeb47d5-5514-40cf-bc4d-52e10543b220.jpg',
      success: function(res) {
        console.log("转发成功");
        if (res.shareTickets == null || res.shareTickets == undefined || res.shareTickets == "") {
          _this.endPanelDisplay();
          console.log("没有群信息，说明分享的是个人 不加道具");
        } else {
          // 云端添加道具数量
          if (_this.item == 1) {
            db.collection('Moyu').doc(_this._id).update({
              data: {
                clock: db.command.inc(1)
              }
            })
          } else if (_this.item == 2) {
            db.collection('Moyu').doc(_this._id).update({
              data: {
                powFire: db.command.inc(1)
              }
            })
          } else if (_this.item == 3) {
            db.collection('Moyu').doc(_this._id).update({
              data: {
                water: db.command.inc(1)
              }
            })
          } else if (_this.item == 4) {
            db.collection('Moyu').doc(_this._id).update({
              data: {
                doubleCoin: db.command.inc(1)
              }
            })
          }
          _this.endPanelDisplay();
          console.log("有群信息 分享的是群 加道具");
        }
      },
      fail: function(res) {
        _this.endPanelDisplay();
        console.log("shareAppMessage fail:", res);
      },
    });
    console.log("跳转分享按钮");
  },
  // 转到结束页面
  endPanelDisplay: function() {
    var _this = this;
    _this.getPanel.active = false;
    _this.jinliPanel.active = false;
    _this.endPanel.active = true;
    _this.endPanel.getChildByName('money').getComponent(cc.Label).string = "+" + _this.money.string;

    const db = wx.cloud.database();
    db.collection('Moyu').where({
        _openid: _this.OPENID,
      })
      .get({
        success: function(res) {
          _this.totalScore = parseInt(_this.money.string) + res.data[0].score;
          if (_this.totalScore >= 300) {
            _this.totalScore = 300;
            _this.endPanel.getChildByName('jinliBar').getChildByName('desc').getComponent(cc.Label).string = '点击锦鲤收获它!';
          } else {
            _this.endPanel.getChildByName('jinliBar').getChildByName('desc').getComponent(cc.Label).string = '再获取 ' + (300 - _this.totalScore) + ' 金币就能收获一条锦鲤!';
          }
          db.collection('Moyu').doc(_this._id).update({
            data: {
              score: _this.totalScore
            }
          })
          _this.endPanel.getChildByName('jinliBar').getChildByName('num').getComponent(cc.Label).string = _this.totalScore.toString() + '/300';
          _this.endPanel.getChildByName('jinliBar').getChildByName('bar').width = 178 * (_this.totalScore / 300);
          console.log("getData_success_get长度不为0", res.data[0]);
        },
        fail: function(res) {
          console.log("getData_fail_get", res);
        },
        complete: function(res) {
          console.log("getData_complete_get222", res);
        }
      })
  },
  // 跳转获得锦鲤页面
  jinliPanelDisplay: function() {
    if (this.totalScore < 300) return;
    this.endPanel.active = false;
    this.jinliPanel.active = true;
  },
  // 分享获得锦鲤
  toShareJinli: function() {
    var _this = this;
    //微信开启群分享
    wx.updateShareMenu({
      withShareTicket: true
    });
    wx.shareAppMessage({
      title: '好友'+ Globals.playername + '邀你玩烧烤之王，赢花语呢喃大奖',
      imageUrl: 'res/raw-assets/0e/0eeb47d5-5514-40cf-bc4d-52e10543b220.jpg',
      success: function(res) {
        console.log("转发成功");
        if (res.shareTickets == null || res.shareTickets == undefined || res.shareTickets == "") {
          console.log("没有群信息，说明分享的是个人 不加道具");
        } else {
          // 云端添加道具数量
          _this.totalScore -= 300;
          db.collection('Moyu').doc(_this._id).update({
            data: {
              koi: db.command.inc(1),
              score: _this.totalScore
            }
          })
          console.log("有群信息 分享的是群 加道具");
        }
        _this.endPanelDisplay();
      },
      fail: function(res) {
        _this.endPanelDisplay();
        console.log("shareAppMessage fail:", res);
      },
    });
    console.log("跳转分享按钮");
  },
  // 游戏暂停
  pauseDisplay: function() {
    cc.audioEngine.pauseAll();
    for (var i = 0; i < Globals.moyuArr.length; i++) {
      Globals.moyuArr[i].getComponent(cc.Button).enabled = false;
    }
    Globals.gameRun = false;
    this.stopPanel.active = true;
  },
  // 继续游戏
  resume: function() {
    cc.audioEngine.resumeAll();
    for (var i = 0; i < Globals.moyuArr.length; i++) {
      Globals.moyuArr[i].getComponent(cc.Button).enabled = true;
    }
    Globals.gameRun = true;
    this.stopPanel.active = false;
  },
  // 重新开始
  restart: function() {
    this.preMan.delAllMoyu();
    cc.audioEngine.stopAll();
    this.stopPanel.active = false;
    this.endPanel.active = false;
    this.getPanel.active = false;
    this.jinliPanel.active = false;
    Globals.gameRun = true; // 判断游戏开始或结束
    Globals.powerBS = 1.0; // 判断火力大小 使用功率计算
    // cc.audioEngine.play(this.gameBgAudio, true);        // 播放音乐
    this.timeCount = 0; // 倒计时扣除时间
    this.totalTimeCount = 180; // 倒计时总时间
    this.powTime = 0; // 火力时间计时
    this.money.string = '0'; // 初始金币为0
    this.powBigTime = 10; // 道具大火时效初始 10秒
    this.powSomleTime = 30; // 道具小火时效初始 30秒
    Globals.resultCoin = 1; // 道具双倍金币效果 初始1倍                  
    this.updateCloud(); // 更新云端数据
    this.totalPowTimeBar.getComponent(cc.ProgressBar).progress = 0.5;
    cc.log('重新开始');
  },
  // 回主页面
  gotoMain: function() {
    cc.director.loadScene("Main", function() {
      cc.log("跳转main场景");
    });
  },
  // 烤焦被收起 扣除时间20秒
  deductionTime: function() {
    this.totalTimeCount -= 20;
  }
});
module.exports = game;